import { useRef, useEffect, useState } from "react";
interface Iporps {
  src: string;
  alt: string;
}
const LozyLoadImage = ({ src, alt }: Iporps) => {
  const [imageSrc, setImageSrc] = useState("");
  const imgRef = useRef<Element | null>(null);

  useEffect(() => {
    let observer: IntersectionObserver | null;
    if (imgRef.current) {
      observer = new IntersectionObserver(
        ([entry]) => {
          if (entry.isIntersecting) {
            setImageSrc(src);
            observer?.unobserve(imgRef.current as Element);
          }
        },
        {
          rootMargin: "0px 0px 200px 0px",
        }
      );
      observer.observe(imgRef.current);
    }
    return () => {
      if (imgRef.current && observer?.unobserve) {
        observer.unobserve(imgRef.current);
      }
    };
  }, [src]);

  return <img ref={(ref) => (imgRef.current = ref)} src={imageSrc} alt={alt} />;
};

export default LozyLoadImage;
